<script setup lang="ts">
import { Group } from 'three'
import {AllowedModelFileTypeList, ModelFileType} from '@/types/web3d'
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter'
import {ThemeVO, ThemeApi} from "@/api/pb/theme";

const message = useMessage()

const theme = inject<Ref<ThemeVO>>('theme')
// 内容 Group
const contentGroup = inject<Group>('contentGroup')!

const showDialog = ref(false)

const uploadRef = ref()

const handleSave = (type: ModelFileType) => {
  new GLTFExporter().parse(
    contentGroup,
    (data: ArrayBuffer | { [key: string]: any }) => {
      handleArrayBuffer(data as ArrayBuffer, type)
    },
    handleExportError,
    { includeCustomExtensions: true }
  )
  // 暂时不需要保存为其他的类型
  // switch (type) {
  //   case ModelFileType.gltf: {
  //     new GLTFExporter().parse(
  //       contentGroup,
  //       (data: ArrayBuffer | { [key: string]: any }) => {
  //         handleArrayBuffer(data as ArrayBuffer, type)
  //       },
  //       handleExportError,
  //       { includeCustomExtensions: true }
  //     )
  //     break
  //   }
    // case ModelFileType.glb: {
    //   new GLTFExporter().parse(
    //     contentGroup,
    //     (data: ArrayBuffer | { [key: string]: any }) => {
    //       handleArrayBuffer(data as ArrayBuffer, type)
    //     },
    //     handleExportError,
    //     { binary: true, includeCustomExtensions: true }
    //   )
    //   break
    // }
  // }
}

const handleArrayBuffer = (
  data: ArrayBuffer | { [key: string]: any } | string,
  type: ModelFileType,
  mimeType: string = 'application/octet-stream'
) => {
  if (!(data instanceof ArrayBuffer)) {
    data = JSON.stringify(data, null, 2)
  }
  const file = new File([data], `${theme!.value.name}.${type}`, { type: mimeType })
  uploadRef.value.handleStart(file)
}

const handleExportError = (err: ErrorEvent) => {
  message.error('保存失败')
  console.error(err)
}

const handleUploadSuccess = async (url: string[]) => {
  await ThemeApi.updateTheme({
    ...theme!.value,
    modelUrl: url[0]
  })
  theme!.value = await ThemeApi.getTheme(theme!.value.id)
  message.success('保存成功')
}
</script>

<template>
<!--  <el-button class="w-full" type="primary" @click="showDialog = true">保存</el-button>-->
  <el-button class="w-full" type="primary" @click="handleSave(ModelFileType.gltf)">保存</el-button>

<!--  <Dialog v-model="showDialog" title="保存类型">-->
<!--    <el-button type="primary" @click="handleSave(ModelFileType.gltf)">GLTF（推荐！）</el-button>-->
<!--    <el-button type="primary" @click="handleSave(ModelFileType.glb)">GLB</el-button>-->
<!--  </Dialog>-->

  <UploadFile
    ref="uploadRef"
    v-show="false"
    :file-type="AllowedModelFileTypeList"
    :file-size="128"
    @success="handleUploadSuccess"
  />
</template>

<style scoped lang="scss"></style>
